package itheima.zuoye.Test2;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionExample {
    // Step 1: Define the Person class
    public static class Person {
        private String name;
        private int age;

        public Person() {
        }

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{name='" + name + "', age=" + age + "}";
        }
    }

    public static void main(String[] args) {
        try {
            // 获取 Person 的字节码 Class
            Class<?> personClass = Person.class;

            // 通过 Class 获取有参构造方法
            Constructor<?> constructor = personClass.getConstructor(String.class, int.class);

            // 调用构造方法，创建 Person 对象
            Object personObj = constructor.newInstance("InitialName", 20);

            // 通过 Class 获取 setName 方法对象
            Method setNameMethod = personClass.getMethod("setName", String.class);

            // 执行 setName 方法对象
            setNameMethod.invoke(personObj, "NewName");

            // 通过 Class 获取 age 的 Field 对象
            Field ageField = personClass.getDeclaredField("age");

            // 设置属性（需要设置 accessible 为 true）
            ageField.setAccessible(true);
            ageField.set(personObj, 25);

            // 输出结果
            System.out.println(personObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
